package com.zrkizzy.service;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhangrongkang
 * @since 2023/11/18
 */
@Service
public class ZookeeperService {

    @Autowired
    private CuratorFramework curatorFramework;

    public void watchNode(String path) {
        CuratorCache curatorCache = CuratorCache.build(curatorFramework, path);
        CuratorCacheListener listener = CuratorCacheListener.builder()
                .forChanges((oldNode, node) -> {
                    System.out.println("旧节点值:  " + new String(oldNode.getData()) + "新节点值:  " + new String(node.getData()));
                })
                .forCreates((node) -> {
                    System.out.println("节点创建值:  " + new String(node.getData()));
                })
                .forDeletes((node) -> {
                    System.out.println("节点被删除值:  " + new String(node.getData()));
                })
                .forInitialized(() -> System.out.println("Cache initialized"))
                .build();
        curatorCache.listenable().addListener(listener);
        curatorCache.start();
    }

}
